package com.hnhs.aop;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hnhs.info.PageInfo;
import com.hnhs.threadLocal.LocalPageInfoUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class PagexAop {
    // 定义切入点
    @Pointcut("@annotation(com.hnhs.pageann.PageX)")
    public void point(){

    }
    //定义环绕通知
    @Around("point()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        RequestAttributes requestAttributes= RequestContextHolder.getRequestAttributes();
        //获取前端传递过来的分页参数
        String pageNum =((ServletRequestAttributes) requestAttributes).getRequest().getParameter("pageNum");
        String pageSize =((ServletRequestAttributes) requestAttributes).getRequest().getParameter("pageSize");
        //判断前端是否发起了分页
        if (!ObjectUtil.isEmpty(pageNum) && !ObjectUtil.isEmpty(pageSize)){
            PageHelper.startPage(Integer.valueOf(pageNum),Integer.valueOf(pageSize));
        }
        //从切入点开始继续往下执行
        Object value=joinPoint.proceed();
        if (value instanceof Page){            Page page= (Page) value;
            Long total = page.getTotal();
            //把total 给赋值一下
            LocalPageInfoUtil.set(PageInfo.builder().total(total).build());
        }

        return value;
    }

}
